package com.saascloud.auth.core;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.HashMap;

/**
 * 根据授权码获得令牌
 *
 * @author liangxuch
 */
@Controller
@Slf4j
public class TokenEndpoint {
    @Autowired
    OAuthConfig oauthConfig;
    @Autowired
    MyAuthorityPermit myAuthorityPermit;

    /**
     * 根据授权码获得令牌
     * code 授权码
     */
    @GetMapping(value = "/login")
    public Object getCodeByAuthorizationCode(String code) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("client_id", oauthConfig.getClientId());
        map.put("client_secret", oauthConfig.getClientSecret());
        map.put("grant_type", "authorization_code");
        map.put("code", code);
        JSONObject oauthClientDetails = myAuthorityPermit.getOauthClientDetails(oauthConfig.getClientId());
        JSONObject data = oauthClientDetails.getJSONObject("data");
        String redirectUri = data.getString("webServerRedirectUri");
        map.put("redirect_uri", redirectUri);
        log.info("授权码authorizationCode--{}--{}", code, JSON.toJSONString(map));
        String token1 = data.getString("token");
        String token = HttpUtil.post(token1, map);
        String accessToken = JSON.parseObject(token).getString("access_token");
        log.info("根据授权码获得令牌token-------{}", accessToken);
        // 携带令牌跳转给前端
        return "redirect:" + data.getString("portalTokenUrl") + accessToken;
    }


}
